package cn.tedu.boot23.controller;

import cn.tedu.boot23.entity.Hero;
import cn.tedu.boot23.utils.DBUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.*;

@Controller
public class HeroController {
    @RequestMapping("/add")
    @ResponseBody
    public String add(Hero hero){
        try (Connection conn = DBUtils.getConn()) {
            String sql = "insert into hero values (null,?,?,?)";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1,hero.getName());
            ps.setString(2,hero.getType());
            ps.setDouble(3,hero.getMoney());
            int i = ps.executeUpdate();
            if (i>0) {
                return "添加成功";
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return "添加失败";
    }
    @RequestMapping("/select")
    @ResponseBody
    public String select(){
        String html = "<center>\n" +
                "    <table border=\"1px\">\n" +
                "        <caption>英雄列表</caption>\n" +
                "        <tr>\n" +
                "            <th>id</th>\n" +
                "            <th>name</th>\n" +
                "            <th>type</th>\n" +
                "            <th>money</th>\n" +
                "        </tr>";
        try (Connection conn = DBUtils.getConn()) {
            String sql = "select id,name,type,money from hero";
            Statement s = conn.createStatement();
            ResultSet rs = s.executeQuery(sql);
            while (rs.next()) {
                int id = rs.getInt(1);
                String name = rs.getString(2);
                String type = rs.getString(3);
                double money = rs.getDouble(4);
                html += "<tr>\n" +
                        "        <td>"+ id +"</td>\n" +
                        "        <td>"+ name +"</td>\n" +
                        "        <td>"+ type +"</td>\n" +
                        "        <td>"+ money +"</td>\n" +
                        "    </tr>";
            }

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        html += " </table>\n" +
                "</center>";
        System.out.println(html);
        return html;
    }
}
